import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;

public class JDBCDemo1 {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // 1. 创建数据库连接Connection
            //connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/csdn", "root", "000907");
            // 也可以通过DataSource获取连接
            DataSource ds = new MysqlDataSource();
            ((MysqlDataSource) ds).setUrl("jdbc:mysql://localhost:3306/csdn?characterEncoding=UTF-8&useSSL=false");
            ((MysqlDataSource) ds).setUser("root");
            ((MysqlDataSource) ds).setPassword("000907");
            connection = ds.getConnection();

            // 2. 创建操作命令Statement 获取全部学生的id和name
            statement = connection.createStatement();

            // 3. 使用操作命令来执行SQL
            String sqlQuery = "SELECT * FROM student";
            resultSet = statement.executeQuery(sqlQuery);

            // 4. 处理结果集ResultSet
            while (resultSet.next()) {
                // Process each row of the result set here
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                // Do something with the retrieved data
                System.out.println("ID: " + id + ", Name: " + name);
            }

            //2. 创建操作命令PreparedStatement  查询id == 1 的学生id和name
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM student WHERE id = ?");

            // 3. 使用操作命令来执行SQL preparedStatement.setInt（参数index，参数值）
            preparedStatement.setInt(1,1);
            ResultSet resultSet1 = preparedStatement.executeQuery();

            // 4. 处理结果集ResultSet
            while (resultSet1.next()) {
                // Process each row of the result set here
                int id = resultSet1.getInt("id");
                String name = resultSet1.getString("name");
                // Do something with the retrieved data
                System.out.println("ID: " + id + ", Name: " + name);
            }



        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 5. 释放资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
